package com.hetang.maijiayun.adaptertools.commons;


import org.slf4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 
 * @className  UrlFilter 
 * @author why
 * @date 2014-5-19 下午7:45:29  
 * @description  过滤请求，检查是否是已设置的请求
 */
public class UrlFilter extends HttpServlet implements Filter {
	private static final long serialVersionUID = 1L;
	private Logger logger = org.slf4j.LoggerFactory.getLogger(UrlFilter.class);
	
	public void doFilter(ServletRequest arg0, ServletResponse arg1,
			FilterChain filterChain) throws IOException, ServletException {
		 	HttpServletRequest request = (HttpServletRequest) arg0;
		    HttpServletResponse rsp=(HttpServletResponse) arg1;
		    // 请求的uri，验证请求有效性
	        String uri = request.getRequestURI();
	        // 处理当当店铺授权回调链接中的view参数
	        String queryString = request.getQueryString();
	        if(uri.contains("/b2c/eshop/authorize/dangdang.ht") && queryString.contains("&view=web")){
	        	rsp.sendRedirect(uri + "?" + queryString.replace("&view=web", ""));
	        	return;
	        } 
	        if(uri.contains(".ht")){
	        	rsp.setHeader("Access-Control-Allow-Credentials", "true");	// FIXME 注释掉方便开发，部署时根据实际情况解开
	        	rsp.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));	// FIXME 注释掉方便开发，部署时根据实际情况解开
//	        	rsp.setHeader("Access-Control-Allow-Origin", "*");	// 必须，否则会报跨域错误
//	        	rsp.addHeader("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE");
	        	rsp.setHeader("Access-Control-Allow-Headers", "Content-Type");	// 必须，否则Controller不能接受json参数
	        	filterChain.doFilter(arg0, arg1);
	        }else if(uri.contains("/css/")){
	        	filterChain.doFilter(arg0, arg1);
	        }else if(uri.contains("/img/")){
	        	filterChain.doFilter(arg0, arg1);
	        }else if(uri.contains("/js/")){
	        	filterChain.doFilter(arg0, arg1);
	        }else if(uri.contains("/fonts/")){
	        	filterChain.doFilter(arg0, arg1);
	        }else if(uri.contains("/websit/")){
	        	filterChain.doFilter(arg0, arg1);
	        }else if(uri.contains("/install_lodop")){
	        	filterChain.doFilter(arg0, arg1);
	        }else if(uri.contains("/author.jsp")){
	        	filterChain.doFilter(arg0, arg1);
	        }else{
	        	request.getRequestDispatcher("/index.html").forward(arg0,arg1);
	        }
	}
	
	public void init(FilterConfig arg0) throws ServletException {
	}
}
